////
////  WXPFaceCameraVC.m
////  MexicoLoan
////
////  Created by WXP on 2025/3/2.
////
//
#import "WXPFaceCameraVC.h"
#import <Photos/Photos.h>
#import <AVFoundation/AVFoundation.h>

@interface WXPFaceCameraVC()<AVCaptureMetadataOutputObjectsDelegate,UIAlertViewDelegate,CAAnimationDelegate,AVCapturePhotoCaptureDelegate>

// 相机相关
@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureDeviceInput *input;
@property (nonatomic, strong) AVCaptureMetadataOutput *output;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
@property (nonatomic, strong) AVCaptureDevice *device;
@property (nonatomic, strong) AVCapturePhotoOutput *ImageOutPut;

@property (nonatomic, strong) WXPNavView * navView;
@property (nonatomic, strong) UIView * viewBottom;

@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) UIImageView *imagePhoto;
@property (nonatomic, strong) UIView * jiancaiView;

@end

@implementation WXPFaceCameraVC

#pragma mark - lazy
- (AVCaptureVideoPreviewLayer *)previewLayer{
    if (_previewLayer == nil) {
        _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
        _previewLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    }
    return  _previewLayer;
}
- (AVCapturePhotoOutput *)ImageOutPut {
    if (!_ImageOutPut) {
        _ImageOutPut = [[AVCapturePhotoOutput alloc] init];
    }
    return _ImageOutPut;
}
// 初始化输入
- (AVCaptureDeviceInput *)input{
    if (_input == nil) {
        _input = [[AVCaptureDeviceInput alloc]initWithDevice:self.device error:nil];
    }
    return _input;
}
// 初始化输出
- (AVCaptureMetadataOutput *)output{
    if (_output == nil) {
        _output = [[AVCaptureMetadataOutput alloc]init];
    }
    return  _output;
}
// 使用AVMediaTypeVideo 指明self.device代表视频，默认使用后置摄像头进行初始化
- (AVCaptureDevice *)device{
    if (_device == nil) {
        _device = [AVCaptureDevice defaultDeviceWithDeviceType:AVCaptureDeviceTypeBuiltInWideAngleCamera mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionFront];
    }
    return _device;
}

- (WXPNavView *)navView
{
    if (_navView == nil) {
        _navView = [WXPNavView  new];
        [_navView resetViewWithTitle:@"Foto en vivo"];
        _navView.titleLabel.textColor = COLOR_WHITE;
        _navView.backgroundColor = [UIColor clearColor];
        _navView.btnService.hidden = true;
        [_navView resetBackImageIsWhite];
        _navView.leftTop = XY(0, 0);
        _navView.blockPop = ^{
            [Global_Nav popViewControllerAnimated:true];
        };
    }
    return  _navView;
}
- (UIView *)viewBottom
{
    if (_viewBottom == nil) {
        _viewBottom = [UIView  new];
        _viewBottom.widthHeight = XY(SCREEN_WIDTH, deviceIsBangsScreen ? 180 : 126);
        _viewBottom.backgroundColor = COLOR_WHITE;
        _viewBottom.leftBottom = XY(0, SCREEN_HEIGHT);
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:_viewBottom.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(16, 16)];
        CAShapeLayer *maskLayer = [CAShapeLayer layer];
        maskLayer.path = path.CGPath;
        _viewBottom.layer.mask = maskLayer;
        UIButton * btn = [UIButton new];
        btn.widthHeight = XY(deviceIsBangsScreen ? 80 : 60, deviceIsBangsScreen ? 80 : 60);
        __weak typeof(btn) weakBtn = btn;
        WEAKSELF
        [btn setNoRepeatActionWithInterval:1 action:^(UIButton * _Nonnull button) {
            typeof(btn) strongBtn = weakBtn;
            if (strongBtn) {
                [NSObject clickFeedback];
                [strongBtn addClickAnimate];
                [weakSelf takePicture];
            }
        }];
        [btn setImage:[UIImage imageNamed:@"icon-face-camera"] forState:UIControlStateNormal];
        btn.centerXCenterY = XY(_viewBottom.width/2, _viewBottom.height/2);
        [_viewBottom addSubview:btn];
    }
    return  _viewBottom;
}
- (UIView *)jiancaiView{
    if (!_jiancaiView) {
        _jiancaiView = [UIView new];
        _jiancaiView.backgroundColor = [UIColor orangeColor];
        _jiancaiView.alpha = 0.4;
    }
    return _jiancaiView;
}
- (UIImageView *)imagePhoto
{
    if (_imagePhoto == nil) {
        _imagePhoto = [[UIImageView alloc] init];
        _imagePhoto.contentMode = UIViewContentModeScaleAspectFit;
        _imagePhoto.userInteractionEnabled = true;
        _imagePhoto.clipsToBounds = YES;
        UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
        [_imagePhoto addGestureRecognizer:tapGestureRecognizer];
    }
    return _imagePhoto;
}
- (void)tapClick:(UITapGestureRecognizer * )tap{
    [self.imagePhoto removeFromSuperview];
}

#pragma mark - viewDidLoad
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.session.isRunning) {
        [self.session stopRunning];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self preferredStatusBarStyle];
    // 打点
    self.view.backgroundColor = [UIColor clearColor];

    [self customCamera];

    [self addShadow];
    [self.view addSubview:self.navView];
    [self.view addSubview:self.viewBottom];
    
//    [self.view addSubview:self.jiancaiView];
    self.jiancaiView.widthHeight = XY(SCREEN_WIDTH-20, self.viewBottom.top-40-[GlobalMethod getNavgationBarHeight]-60);
    self.jiancaiView.centerXTop = XY(SCREEN_WIDTH/2, [GlobalMethod getNavgationBarHeight]+60);
}
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

#pragma mark - 添加蒙层
- (void)addShadow
{
    UIImageView * imageView = [UIImageView new];
    imageView.widthHeight = XY(SCREEN_WIDTH, SCREEN_WIDTH/1125*2436);
    imageView.leftTop = XY(0, -20);
    imageView.image = [UIImage imageNamed:@"icon-face-shadow"];
    [self.view addSubview:imageView];

    UILabel * titleLabel = [UILabel new];
    titleLabel.textColor = COLOR_WHITE;
    titleLabel.numberOfLines = 0;
    titleLabel.lineSpace = (2);
    titleLabel.fontNum = 12;
    [titleLabel fitTitle:@"Sitúa tu cara en el marco y captura una imagen." variable:0];
    titleLabel.centerXTop = XY(SCREEN_WIDTH/2, [GlobalMethod getNavgationBarHeight]+44);
    [self.view addSubview:titleLabel];
}

#pragma mark - 自定义相机
- (void)customCamera{
    [self showLoadingView];

    // 初始化会话
    self.session = [[AVCaptureSession alloc] init];
    [self configureSessionPreset];
    [self configureSessionInputOutput];
    [self configurePreviewLayer];

    // 异步启动相机
    [self startCameraSession];

    // 配置相机参数
    [self configureCameraSettings];
}

- (void)configureSessionPreset {
    if ([self.session canSetSessionPreset:AVCaptureSessionPresetPhoto]) {
        self.session.sessionPreset = AVCaptureSessionPresetPhoto;
    }
}

- (void)configureSessionInputOutput {
    // 添加输入
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    // 添加输出
    if ([self.session canAddOutput:self.ImageOutPut]) {
        [self.session addOutput:self.ImageOutPut];
    }
}

- (void)configurePreviewLayer {
    [self.view.layer addSublayer:self.previewLayer];
}

- (void)startCameraSession {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self.session startRunning];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.loadingView hideLoading];
        });
        // 打点
        //[GlobalMethod userBehaviorRecordWithPageName:@"VerifyKtp" action:@"ID_Front_Camera_Init" extInfo:nil];
    });
}

- (void)configureCameraSettings {
    if ([self.device lockForConfiguration:nil]) {
        if ([self.device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
            [self.device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
        }
        [self.device unlockForConfiguration];
    }
}

#pragma mark - 拍照
// 拍照
- (void)takePicture {
    // 确保会话在运行
    if (!self.session.isRunning) {
        NSLog(@"Camera session is not running!");
        return;
    }
    // 检查是否有活跃的视频连接
    AVCaptureConnection *videoConnection = [self.ImageOutPut connectionWithMediaType:AVMediaTypeVideo];
    if (!videoConnection || !videoConnection.isEnabled) {
        NSLog(@"No active video connection!");
        return;
    }
    
    // 创建照片设置并设置闪光灯模式
    AVCapturePhotoSettings *photoSettings = [AVCapturePhotoSettings photoSettings];
    if ([self.device hasFlash]) {
        photoSettings.flashMode = AVCaptureFlashModeOff; // 在这里设置闪光灯模式
    }
    // 捕获照片
    [self.ImageOutPut capturePhotoWithSettings:photoSettings delegate:self];
}

#pragma mark - 拍照防抖
- (void)configureCameraPreview:(AVCaptureDevice *)camera {
    for (AVCaptureConnection *connection in self.ImageOutPut.connections) {
        for (AVCaptureInputPort *port in [connection inputPorts]) {
            if ([[port mediaType] isEqual:AVMediaTypeVideo]) {
                if ([connection isVideoStabilizationSupported]) {
                    connection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeAuto;
                    NSLog(@"视频稳定已启用");
                } else {
                    NSLog(@"该设备的当前格式不支持视频稳定。");
                }
                break;
            }
        }
    }
}

#pragma mark - AVCapturePhotoCaptureDelegate
- (void)captureOutput:(AVCapturePhotoOutput *)output
    didFinishProcessingPhoto:(AVCapturePhoto *)photo
                     error:(NSError *)error {
    if (error) {
        NSLog(@"Error capturing photo: %@", error);
        return;
    }
    
    // 立即停止相机预览，锁定当前画面
    [self.session stopRunning];

    NSData *imageData = [photo fileDataRepresentation];
    if (imageData) {
        UIImage *capturedImage = [UIImage imageWithData:imageData];

        // 确保图片方向正确
        UIImageOrientation orientation = UIImageOrientationRight;
        self.image = [[UIImage alloc] initWithCGImage:capturedImage.CGImage
                                               scale:capturedImage.scale
                                         orientation:orientation];
        
        // 确保在正确的方向下获取尺寸
        CGSize imageSize = self.image.size;
        
        // 如果需要，先将图片转换为正确方向
        UIGraphicsBeginImageContextWithOptions(imageSize, NO, self.image.scale);
        [self.image drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
        UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        // 计算中心裁剪区域
        CGFloat cropWidth = imageSize.width / 2.0;
        CGFloat cropHeight = imageSize.height / 2.0;
        CGFloat offsetX = (imageSize.width - cropWidth) / 2.0;
        CGFloat offsetY = (imageSize.height - cropHeight) / 2.0-200;
        
        // 创建裁剪区域
        CGRect cropRect = CGRectMake(offsetX, offsetY, cropWidth, cropHeight);
        
        // 执行裁剪
        CGImageRef croppedImageRef = CGImageCreateWithImageInRect(normalizedImage.CGImage, cropRect);
        
        // 创建新的裁剪后的图片
        self.image = [UIImage imageWithCGImage:croppedImageRef
                                       scale:self.image.scale
                                 orientation:UIImageOrientationUp];
        
        // 释放资源
        CGImageRelease(croppedImageRef);
        
        // 更新显示
        //self.imagePhoto.image = self.image;
        //self.imagePhoto.widthHeight = XY(SCREEN_WIDTH, SCREEN_HEIGHT);
        //self.imagePhoto.leftTop = XY(0, 0);
        //UIWindow * window = [UIApplication sharedApplication].windows.firstObject;
        //[window endEditing:true];
        //[window addSubview:self.imagePhoto];
        
        if (self.session.isRunning) {
            [self.session stopRunning];
        }
        [self requestOSSUploadLive];
    }
}

#pragma mark - request
// 活体照片识别
- (void)requestOSSUploadLive{
//    if(self.isLiveness){
        //[GlobalMethod userBehaviorRecordWithPageName:@"VerifyFacial" action:@"Liveness_Click" extInfo:nil];
//    }
    [self.loadingView hideLoading];
    [self.loadingView resetFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) viewShow:self.view];
    [RequestApi requestAuthLiveWithImage:self.image phone:self.phone livenChannelEnum:self.livenChannelEnum liveTypeEnum: self.liveTypeEnum delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        // NSLog(@" ------ %@",response);
        if([[response stringValueForKey:RESPONSE_CODE] intValue] == [RESPONSE_CODE_200 intValue]){
            // 成功
            if(self.liveType == 2){
                [GlobalMethod hitPointWithPageName:KEY_VerifyFacial action:KEY_Liveness_Success extInfo:nil];
            }
            if(self.liveType == 1){
                // 登录活体
            }
            
            NSDictionary * data = [response dictionaryValueForKey:RESPONSE_DATA];
            if(self.blockUploadSuccess){
                self.blockUploadSuccess([data stringValueForKey:KEY_url], [data stringValueForKey:KEY_photoName], [data stringValueForKey:KEY_livenessId]);
            }
        }else{
            // 失败
            if(self.liveType == 2){
                [GlobalMethod hitPointWithPageName:KEY_VerifyFacial action:KEY_Liveness_Failure extInfo:@{@"errorMsg": [response stringValueForKey:RESPONSE_MESSAGE]}];
            }
            if(self.liveType == 1){
                // 打点 - 登录活体
                [GlobalMethod hitPointWithPageName:KEY_LoginFacial action:KEY_Liveness_Failure extInfo:@{@"errorMsg": [response stringValueForKey:RESPONSE_MESSAGE]}];
            }
            
            if(self.blockUploadFail){
                self.blockUploadFail([response stringValueForKey:RESPONSE_MESSAGE]);
            }
            // 切换活体渠道
            [self changeLiveChanel];
        }
        [Global_Nav popViewControllerAnimated:true];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        // 失败
        if(self.liveType == 2){
            [GlobalMethod hitPointWithPageName:KEY_VerifyFacial action:KEY_Liveness_Failure extInfo:@{@"errorMsg": errorStr}];
        }
        if(self.liveType == 1){
            // 打点 - 登录活体
            [GlobalMethod hitPointWithPageName:KEY_LoginFacial action:KEY_Liveness_Failure extInfo:@{@"errorMsg": errorStr}];
        }
        
        if(self.blockUploadFail){
            self.blockUploadFail(errorStr);
        }
        // 切换活体渠道
        [self changeLiveChanel];
        [Global_Nav popViewControllerAnimated:true];
    }];
}

// 切换活体渠道
- (void)changeLiveChanel{
    // 切换活体渠道接口
    // 登录活体切换需要传phone
    // 静默活体识别失败 应该是会自动切换渠道的，你不用调切换的
}

@end
